package com.gitee.wsl.text.buffer.storage

import kotlinx.atomicfu.atomic

interface StringBuilderPool {

    fun getBuilderForCapacity(capacity: Int): StringBuilder
    fun recycleBuilder(builder: StringBuilder)

    companion object {
        val Unpooled = object : StringBuilderPool {
            override fun getBuilderForCapacity(capacity: Int): StringBuilder =
                StringBuilder(capacity)

            override fun recycleBuilder(builder: StringBuilder) {}
        }

        fun singleBuilder() = object : StringBuilderPool {
            private var cache = atomic<StringBuilder?>(null)

            override fun getBuilderForCapacity(capacity: Int): StringBuilder {
                val builder = cache.value
                return if (builder != null && cache.compareAndSet(builder, null)) {
                    builder
                } else {
                    StringBuilder(capacity)
                }
            }

            override fun recycleBuilder(builder: StringBuilder) {
                builder.clear()
                cache.compareAndSet(null, builder)
            }
        }
    }
}